/**
 * Ant Design Pro v4 use `@ant-design/pro-layout` to handle Layout.
 * You can view component api by:
 * https://github.com/ant-design/ant-design-pro-layout
 */
import ProLayout, {MenuDataItem, BasicLayoutProps as ProLayoutProps, Settings,} from '@ant-design/pro-layout';
import React, {ReactNode, useEffect, useMemo, useState} from 'react';
import {Link, history} from 'umi';
//import logo from '../assets/logo.svg';
import styles from './BasicLayout.less';
import {
  FullscreenOutlined,
  HomeOutlined,
  KeyOutlined,
  LogoutOutlined,
  FullscreenExitOutlined,
  QuestionCircleOutlined, MenuOutlined
} from "@ant-design/icons/lib";
import settings from "../../config/defaultSettings";
import {Layout, Modal, Tabs} from "antd";
import classNames from "classnames";
import {getCurrentUserId, getPageQuery, listToTree, setCurrentUser} from "@/utils/utils";
import {stringify} from "qs";
import service from "@/layouts/service";
import onlineUserService from "@/pages/sys/onlineUser/service";
import {SysUserModel} from "@/pages/sys/user/data";
import ModifyPasswordEdit from "@/pages/sys/account/components/ModifyPasswordEdit";
import {SysModuleModel} from "@/pages/sys/module/data";
import useDialog from "@/hooks/useDialog";

const {Header, Footer} = Layout;

export interface BasicLayoutProps extends ProLayoutProps {
  breadcrumbNameMap: {
    [path: string]: MenuDataItem;
  };
  route: ProLayoutProps['route'] & {
    authority: string[];
  };
  settings: Settings;
}

// export interface MenuItem {
//   path?: string;
//   name?: string;
//   children?: MenuItem[];
// }

// const RightContent = (
//   <div className={styles.nav}>
//     <ul>
//       <li>
//         <a>
//           <HomeOutlined/>
//           我的主页
//         </a>
//       </li>
//       <li>
//         <a>
//           <KeyOutlined/>
//           修改密码
//         </a>
//       </li>
//       <li>
//         <a>
//           <LogoutOutlined/>
//           安全退出
//         </a>
//       </li>
//     </ul>
//   </div>
// );


interface TabItemModel {
  key: string
  title: string | ReactNode,
  closable: boolean,
  module: any,
}


const BasicLayout: React.FC<BasicLayoutProps> = (props) => {
  const {children} = props;
  const [user, setUser] = useState<SysUserModel>();
  const [isFullScreen, setIsFullScreen] = useState(false);
  // const [collapsed, setCollapsed] = useState(true);
  const [tabsActiveKey, setTabsActiveKey] = useState('');
  const [tabsList, setTabsList] = useState<TabItemModel[]>([]);
  const [menus, setMenus] = useState([]);
  const [openKeys, setOpenKeys] = useState<string[]>([]);
  const [siderWidth, setSiderWidth] = useState<number>(() => {
    const w = localStorage.getItem('xci-antd-pro-menu-width');
    return Boolean(w) ? Number(w) : 256;
  });
  const modifyPasswordOperate = useDialog();

  //添加主页
  useEffect(() => {
    setTabsList(p => {
      p.push({key: '0', title: '主页', module: {webUrl: '/', webCls: 'icon-home'}, closable: false});
      return p;
    });
    setTabsActiveKey('0');//激活
  }, []);

  //激活当前用户
  useEffect(() => {
    let timeId: any;
    const timeout = 20000;
    const callback = function () {
      const currentUserId = getCurrentUserId();
      currentUserId && onlineUserService.active(currentUserId).catch();
      timeId = setTimeout(callback, timeout);
    };

    timeId = setTimeout(callback, timeout);

    // 返回一个函数来进行额外的清理工作:
    return function cleanup() {
      if (timeId) clearTimeout(timeId);
    };
  });


  //读取用户菜单
  useEffect(() => {
    service.selectCurrentUserPermissionFromCache().then(p => {
      if (p.success === false) return;
      const modules = p.data.modules;

      // if (modules && modules[0].id) {
      //   // @ts-ignore
      //   setOpenKeys([modules[0].id]);
      // }

      let esz: string[] = [];
      modules.forEach((p: SysModuleModel) => {
        p.expand && esz.push(p.id);
      });
      setOpenKeys(esz);

      const user: SysUserModel = p.data.user;
      setUser(user);

      setMenus(modules);

      if (location.pathname && location.pathname !== '/') {
        const module = modules.find((x: any) => x.webUrl === location.pathname);
        if (module) {
          addTabItem(modules, module.id);
        }
      }
    });
  }, []);

  const goPage = (key: string) => {
    //加载页面
    const tabItem = tabsList.find(p => p.key === key);
    if (tabItem) {
      history.push(tabItem.module.webUrl);
    }
  };

  const addTabItem = (modules: any[], key: string) => {
    const module: any = modules.find((p: any) => p.id === key);
    if (!module) {
      return;
    }
    const tabItem = tabsList.find(p => p.key === key);
    if (!tabItem) {//新增
      setTabsList(p => {
        p.push({key, title: module.name, module, closable: true});
        return p;
      })
    }
    setTabsActiveKey(key);//激活
  };

  const removeTabItem = (targetKey: any) => {
    let lastIndex = 0;
    tabsList.forEach((pane, i) => {
      if (pane.key === targetKey) {
        lastIndex = i - 1;
      }
    });
    let key = tabsActiveKey;
    const panes = tabsList.filter(pane => pane.key !== targetKey);
    if (panes.length && tabsActiveKey === targetKey) {
      if (lastIndex >= 0) {
        key = panes[lastIndex].key;
      } else {
        key = panes[0].key;
      }
    }
    setTabsList(panes)
    if (tabsActiveKey !== key) {
      goPage(key);
    }
    setTabsActiveKey(key);
  }

  const getMenuData = () => {
    const mdata = menus
      .filter((p: any) => p.web === true && p.menu === true)
      .map((p: any) => ({
        id: p.id,
        key: p.id,
        parentId: p.parentId,
        path: p.webUrl || '',
        name: p.name,
        webCls: p.webCls,
      }));
    return listToTree(mdata);
  }

  const HeaderLayout = useMemo(() => (
    <Header className={styles.header}>
      {/*<div className={styles.logo}>*/}
      {/*  <img alt="logo" src={logo}/>*/}
      {/*</div>*/}
      <div className={classNames(styles.title, styles.kai)} style={{color: 'white'}}>
        西交投信息系统开发平台
        <div className={styles.subtitle} style={{color: 'yellow'}}>
          测试版
        </div>
      </div>
      <div className={styles.nav}>
        <ul>
          <li>
            <a title="导航菜单" onClick={() => {
              const w = localStorage.getItem('xci-antd-pro-menu-width');
              const width = Boolean(w) && Number(w) > 0 ? 0 : 256;
              localStorage.setItem('xci-antd-pro-menu-width', String(width));
              setSiderWidth(width);
            }}>
              <MenuOutlined/>
              <span>导航菜单</span>
            </a>
          </li>
          <li>
            <a title="我的主页">
              <HomeOutlined/>
              <span>我的主页</span>
            </a>
          </li>
          <li>
            <a title="修改密码" onClick={() => {
              modifyPasswordOperate.show();
            }}>
              <KeyOutlined/>
              <span>修改密码</span>
            </a>
          </li>
          <li>
            <a title="全屏" onClick={async () => {
              if (!isFullScreen) {
                await document.documentElement.requestFullscreen();
              } else {
                await document.exitFullscreen();
              }
              setIsFullScreen(p => !p);
            }}>
              {
                isFullScreen ? (<><FullscreenExitOutlined/><span>退出全屏</span></>)
                  : (<><FullscreenOutlined/><span>全屏</span></>)
              }
            </a>
          </li>
          <li>
            <a title="安全退出" onClick={() => {
              Modal.confirm({
                title: '系统提示',
                icon: <QuestionCircleOutlined/>,
                okText: '确定',
                cancelText: '取消',
                content: '您确定要退出系统吗？',
                onOk() {
                  //注销
                  const {redirect} = getPageQuery();
                  //调用注销后台方法
                  //注销成功后,删除token,页面跳转
                  setCurrentUser(null);
                  if (window.location.pathname !== '/login' && !redirect) {
                    history.replace({
                      pathname: '/login',
                      search: stringify({
                        redirect: window.location.href,
                      }),
                    });
                  }
                }
              });
            }}>
              <LogoutOutlined/>
              <span>安全退出</span>
            </a>
          </li>
        </ul>
      </div>
    </Header>
  ), []);

  const TabsLayout = (
    <Tabs activeKey={tabsActiveKey}
          hideAdd={true}
          size="small"
          type="editable-card"
          style={{backgroundColor: "#f8fafe"}}
          tabBarStyle={{margin: '2px 1px 0 5px'}}
          onChange={(key) => {
            setTabsActiveKey(key);
            goPage(key);
          }}
          onEdit={(targetKey, action) => {
            if (action === 'add') return;
            removeTabItem(targetKey);
          }}
    >
      {tabsList.map(t => (
        <Tabs.TabPane tab={(<><i className={t.module.webCls}/> {t.title}</>)} key={t.key} closable={t.closable}/>
      ))}
    </Tabs>
  );

  const FooterLayout = useMemo(() => (
    <Footer className={styles.footer}>
      <div className={styles.left}>
        欢迎您：
        <span className={styles.name}>{user?.name} - {user?.account} - {user?.deptName}</span>
      </div>
      <div className={styles.right}>
        西安交通信息投资营运有限公司 版权所有
      </div>
    </Footer>
  ), [user]);

  const MainLayout = (
    <ProLayout
      className={styles.basicLayout}
      // logo={logo}
      // openKeys={openKeys}
      // onOpenChange={keys=>setOpenKeys(keys)}
      menuRender={(props, dom) => {
        return siderWidth > 0 ? dom : null;
      }}
      menuHeaderRender={false}
      menuItemRender={(menuItemProps, defaultDom) => {
        const dom = (<><i className={menuItemProps.webCls}/> {defaultDom}</>)
        if (!menuItemProps.path) {
          return dom;
        }
        return <Link to={menuItemProps.path}>{dom}</Link>;
      }}
      subMenuItemRender={(menuItemProps, defaultDom) => {
        return (<><i className={menuItemProps.webCls}/> {defaultDom}</>)
      }}
      breadcrumbRender={() => []}
      headerRender={false}
      menuDataRender={() => getMenuData()}
      fixSiderbar={false}
      menuProps={{
        onClick: (e) => {
          addTabItem(menus, e.key);
        }
      }}
      // rightContentRender={() => RightContent}
      {...props}
      {...settings}
    >
      {TabsLayout}
      {children}
    </ProLayout>
  );

  return (
    <Layout className={styles.layout}>
      {HeaderLayout}
      {MainLayout}
      {FooterLayout}
      {modifyPasswordOperate.visible && <ModifyPasswordEdit {...modifyPasswordOperate}/>}
    </Layout>
  );
};
export default BasicLayout;

